package com.xk.ucs.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.xk.ucs.config.GlobalSetting;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zsx
 * @Description:
 * @DateTime: 2024/3/27 11:31
 */
@Service
@Slf4j
public class HeartBeatService {
	@Value("${check-version.download-url}")
	private  String downloadUrl;
	@Value("${check-version.save-path}")
	private  String savePath;

	@Autowired
	private AdminRemoteService adminRemoteService;
	ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
	private static Timer timer = new Timer();
	@Value("${check-version.sys-version}")
	private int sysVersion;

	@Autowired
	private AdminRemoteService remoteService;


	public void reportHeartBean() {
		//上报一次后定时上报
		this.doUpdate();
		scheduledThreadPool.scheduleAtFixedRate(this::doUpdate, 0, (new Random().nextInt(100)) + 5 * 60,
				TimeUnit.SECONDS);
		checkDownLoad();
	}

	private void doDownNewVersion(){
		try {
            Map<String, Object> box = adminRemoteService.getBox(GlobalSetting.getInstance().getBoxNo());
            int planVersion = NumberUtil.parseInt(box.get("planVersion")==null?"":box.toString());
//            String planMd5 = box.get("planMd5");
            if(planVersion>sysVersion){
                log.error("发现新版本 {}", planVersion);//记录
				Path tempFilePath = Files.createTempFile("ucs.jar", "temp");
				long l = HttpUtil.downloadFile(downloadUrl, savePath);
				log.info("新版本文件下载完成，大小:{}KB",l/1000);
				if (l>0) {
                    log.info("自动结束进程");
                    System.exit(0);
                } else {
                    log.info("下载失败");
                }
            }
		} catch (Exception e) {
			log.error("更新异常", e);
		}
	}

	public boolean doUpdate () {
		Map<String, Object> box = adminRemoteService.getBox(GlobalSetting.getInstance().getBoxNo());
		box.put("currentVersion",sysVersion);
		box.put("updateTime",new Date());
		box.put("boxNo",GlobalSetting.getInstance().getBoxNo());
		return adminRemoteService.updateBox(box);
	}



	private void checkDownLoad() {
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				doDownNewVersion();
			}
		},0, (new Random().nextInt(100*1000)) + 5 * 60*1000);

	}
}
